import {
  app, BrowserWindow, Menu,
  MenuItem,
  ipcMain,
  Tray,
  nativeImage,
  BrowserView,
  session,
} from 'electron'
// import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import fs from 'fs'
import { ref } from 'vue'
import { createDataTable } from './db/sqlite3db'
// const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null
function createWindow() {
  win = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    frame: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
      nodeIntegration: true,    // 是否集成 Nodejs
      contextIsolation: false,
      // 关闭同源策略 解决跨域
      webSecurity: false,
      // 允许使用webview标签
      webviewTag: true,
      partition: 'persist:authtify'
    },
  })
  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    // win?.webContents.send('main-process-message', (new Date).toLocaleString())
    // 设置cookie
    const cookie = {
      url: 'http://192.168.10.7:5000/authtify/#/homePage',
      name: 'test_cookie_name',
      value: 'test_cookie_value',
    };
    session.defaultSession.cookies.set(cookie).then(() => {
      console.log('set cookie success');
      // 设置cookie后，获取cookie
      session.defaultSession.cookies.get({ url: 'http://192.168.10.7:5000/authtify/#/homePage' })
        .then((cookies) => {
          // console.log('get cookie success', cookies)
        }).catch((error) => {
          console.log(error)
        })
    });
  })

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
  const icon = nativeImage.createFromPath(path.join(process.env.VITE_PUBLIC, 'release.png'))
  let tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Item1', type: 'radio' },
    { label: 'Item2', type: 'radio' },
    { label: 'Item3', type: 'radio', checked: true },
    { label: 'Item4', type: 'radio' }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
  // // 定义菜单
  // const menu = new Menu();
  // menu.append(new MenuItem({ label: '复制', role: 'copy' }));
  // menu.append(new MenuItem({ label: '粘贴', role: 'paste' }));
  // menu.append(new MenuItem({ label: '刷新', role: 'reload' }));
  // menu.append(new MenuItem({ label: '全选', role: 'selectall' }));
  // menu.append(new MenuItem({ label: '剪切', role: 'cut' }));
  // menu.append(new MenuItem({ label: '删除', role: 'delete' }));
  // menu.append(new MenuItem({ label: '取消', role: 'undo' }));
  // menu.append(new MenuItem({ label: '重置', role: 'redo' }));
  // 监听window的contextmenu事件
  win.webContents.on('context-menu', (e, params) => {
    e.preventDefault(); // 阻止默认的右键菜单

    // 创建自定义菜单
    const menu = Menu.buildFromTemplate([
      { label: '自定义项1', click: () => console.log('自定义项1被点击') },
      { label: '自定义项2', click: () => console.log('自定义项2被点击') },
      { type: 'separator' }, // 分隔线
      { label: '自定义项3', click: () => console.log('自定义项3被点击') }
    ]);

    // 将自定义菜单显示在鼠标位置
    menu.popup({ window: win, x: params.x, y: params.y });
  });
  let timer = ref()

  let callReminder
  ipcMain.on('create-notification', (_, message) => {
    callReminder = new BrowserWindow({
      width: 300, // 窗口宽度
      height: 200, // 窗口高度
      x: message.width - 300, // 窗口的水平位置
      y: message.height - 200, // 窗口的垂直位置
      frame: false, // 无边框
      webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
        nodeIntegration: true,    // 是否集成 Nodejs
        contextIsolation: false,
        // 关闭同源策略 解决跨域
        webSecurity: false,
      },
    });
    callReminder.loadURL('http://192.168.10.7:9999/#/callReminder')

    // 替代webview标签
    // const view = new BrowserView()
    // callReminder.setBrowserView(view)
    // view.setBounds({ x: 0, y: 0, width: 300, height: 300 })
    // view.webContents.loadURL('https://electronjs.org')
  })

  ipcMain.on('call-response', (_, type) => {
    callReminder.close()
  })

  ipcMain.on('message', (_, message) => {
    if (message === 'start') {
      if (timer.value) return
      tray.setImage(path.join(process.env.VITE_PUBLIC, 'release_transparent.png'))
      let count = 0
      timer.value = setInterval(() => {
        count++
        if (count % 2 == 0) {
          tray.setImage(path.join(process.env.VITE_PUBLIC, 'release_transparent.png'))
        } else {
          tray.setImage(path.join(process.env.VITE_PUBLIC, 'release.png'))
        }
      }, 500)
    } else {
      clearInterval(timer.value)
      timer.value = null
      tray.setImage(path.join(process.env.VITE_PUBLIC, 'release.png'))
    }
  })
  // createDataTable()
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

app.whenReady().then(createWindow)
